<template>
  <el-dialog v-model="visible" title="帖子详情" width="80%" top="5vh" @close="handleClose">
    <div v-if="post && post.forumPost" class="row g-0">
      <div class="col-md-7 border-end">
        <div class="p-4">
          <div class="d-flex mb-3">
            <el-avatar :size="48"
               src='/images/forum.png'
              class="me-2" />
            <div>
              <h6 class="mb-0">
                <span v-if="post.forumPost.authorId === currentUserId" class="author-me">我</span>
                <span v-else>用户ID: {{ post.forumPost.authorId }}</span>
              </h6>
              <small class="text-muted">{{ dayjs(post.forumPost.createTime).fromNow() }}</small>
            </div>
          </div>
          <h5 class="mb-3">{{ post.forumPost.title }}</h5>
          <div class="mb-4" v-html="post.forumPost.content"></div>

          <div class="post-images mb-4">
          </div>

          <div class="d-flex justify-content-between align-items-center">
            <div>
              <el-button size="small" @click="toggleLike">
                <i :class="['bi', liked ? 'bi-heart-fill text-danger' : 'bi-heart']" class="me-1"></i> {{ likeCount }}
              </el-button>
              <el-button size="small" class="me-2">
                <i class="bi bi-bookmark me-1"></i> 收藏
              </el-button>
              <el-button size="small">
                <i class="bi bi-share me-1"></i> 分享
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-5">
        <div class="d-flex flex-column h-100">
          <div class="p-3 border-bottom">
            <h6 class="mb-0">评论 <span class="comment-count">{{ post.replyList ? post.replyList.length : 0 }}</span></h6>
          </div>
          <div class="comment-list p-3 flex-grow-1 overflow-auto" style="max-height: 400px;">
            <!-- <div class="mb-3" v-for="comment in post.replyList.slice().reverse()" :key="comment.id">
              <div class="d-flex mb-2">
                <el-avatar :size="32" src="https://placeholder.pics/svg/32/DEDEDE/555555/用户" class="me-2" />
                <div>
                  <h6 class="mb-0 fs-6">
                    <span v-if="comment.authorId === currentUserId" class="author-me">我</span>
                    <span v-else>用户ID: {{ comment.authorId }}</span>
                  </h6>
                  <small class="text-muted">{{ dayjs(comment.createTime).fromNow() }}</small>
                </div>
              </div>
              <div class="ms-5 mb-2">{{ comment.content }}</div>
              <div class="ms-5">
                <el-button size="small" text class="me-3"><i class="bi bi-heart"></i> 点赞</el-button>
                <el-button size="small" text><i class="bi bi-reply"></i> 回复</el-button>
              </div>
            </div> -->
            <div class="mb-3" v-for="comment in hierarchicalReplies" :key="comment.id"
              :ref="el => setCommentRef(el, comment.id)" @contextmenu.prevent="showReplyContextMenu($event, comment)">
              <div class="d-flex mb-2">
                <el-avatar :size="32"
                  src='/images/forum.png'
                  class="me-2" />
                <div>
                  <h6 class="mb-0 fs-6">
                    <span v-if="comment.authorId === currentUserId" class="author-me">我</span>
                    <span v-else>用户ID: {{ comment.authorId }}</span>
                    <span v-if="comment.isTutorReply === 1" class="text-warning ms-1">（导师）</span>
                  </h6>
                  <small class="text-muted">{{ dayjs(comment.createTime).fromNow() }}</small>
                </div>
              </div>
              <div class="ms-5 mb-2">{{ comment.content }}</div>
              <div class="ms-5">
                <el-button size="small" text class="me-3" @click="toggleCommentLike(comment)">
                  <i :class="['bi', likedCommentIds.has(comment.id) ? 'bi-heart-fill text-danger' : 'bi-heart']"></i> 点赞
                </el-button>
                <el-button size="small" text @click="showSubReplyInput(comment)" v-if="!userStore.isAdmin"><i
                    class="bi bi-reply"></i>
                  回复</el-button>
              </div>

              <div v-if="replyingTo && replyingTo.id === comment.id" class="sub-reply-input ms-5 mt-2">
                <el-input v-model="subReplyContent" :placeholder="`回复 @${comment.authorId}`" size="small">
                  <template #append>
                    <el-button @click="sendSubReply" :icon="Position" />
                  </template>
                </el-input>
              </div>

              <!-- <div v-if="comment.children && comment.children.length > 0"
                class="sub-reply-list ms-5 ps-3 mt-2 border-start">
                <div class="mb-3" v-for="childComment in comment.children" :key="childComment.id">
                  <div class="d-flex mb-2">
                    <el-avatar :size="24" src="https://placeholder.pics/svg/24/DEDEDE/555555/用户" />
                    <div class="ms-2">
                      <h6 class="mb-0 fs-6">
                        <span v-if="childComment.authorId === currentUserId" class="author-me">我</span>
                        <span v-else>用户ID: {{ childComment.authorId }}</span>
                      </h6>
                      <small class="text-muted">{{ dayjs(childComment.createTime).fromNow() }}</small>
                    </div>
                  </div>
                  <div class="ms-5 mb-2">{{ childComment.content }}</div>
                  <div class="ms-5">
                    <el-button size="small" text class="me-3" @click="toggleCommentLike(childComment)">
                      <i
                        :class="['bi', likedCommentIds.has(childComment.id) ? 'bi-heart-fill text-danger' : 'bi-heart']"></i>
                      点赞
                    </el-button>
                    <el-button size="small" text @click="showSubReplyInput(childComment)"><i class="bi bi-reply"></i>
                      回复</el-button>
                  </div>
                </div>
              </div> -->
              <div v-if="comment.children && comment.children.length > 0"
                class="sub-reply-list ms-5 ps-3 mt-2 border-start">
                <div class="mb-3" v-for="childComment in comment.children"
                  :ref="el => setCommentRef(el, childComment.id)" :key="childComment.id"
                  @contextmenu.prevent="showReplyContextMenu($event, childComment)">
                  <div class="d-flex mb-2">
                    <el-avatar :size="24"
                      src='/images/forum.png' />
                    <div class="ms-2">
                      <h6 class="mb-0 fs-6">
                        <span v-if="childComment.authorId === currentUserId" class="author-me">我</span>
                        <span v-else>用户ID: {{ childComment.authorId }}</span>
                        <span v-if="childComment.isTutorReply === 1" class="text-warning ms-1">（导师）</span>
                        <span v-if="childComment.fromReply !== comment.id">
                          <span class="text-muted mx-1">回复</span>
                          <span class="text-primary">@用户{{post.replyList.find(r => r.id ===
                            childComment.fromReply)?.authorId
                          }}</span>
                        </span>
                      </h6>
                      <small class="text-muted">{{ dayjs(childComment.createTime).fromNow() }}</small>
                    </div>
                  </div>
                  <div class="ms-5 mb-2">{{ childComment.content }}</div>
                  <div class="ms-5">
                    <el-button size="small" text class="me-3" @click="toggleCommentLike(childComment)">
                      <i
                        :class="['bi', likedCommentIds.has(childComment.id) ? 'bi-heart-fill text-danger' : 'bi-heart']"></i>
                      点赞
                    </el-button>
                    <el-button size="small" text @click="showSubReplyInput(childComment)" v-if="!userStore.isAdmin">
                      <i class="bi bi-reply"></i> 回复
                    </el-button>
                  </div>
                  <div v-if="replyingTo && replyingTo.id === childComment.id" class="sub-reply-input mt-2">
                    <el-input v-model="subReplyContent" :placeholder="`回复 @用户${childComment.authorId}`" size="small">
                      <template #append>
                        <el-button @click="sendSubReply" :icon="Position" />
                      </template>
                    </el-input>
                  </div>
                </div>
              </div>
            </div>
            <el-empty v-if="!post.replyList || post.replyList.length === 0" description="暂无评论" />
          </div>
          <template v-if="!userStore.isAdmin">
            <div class="p-3 border-top mt-auto">
              <div class="d-flex">
                <el-avatar :size="32"
                   src='/images/forum.png'
                  class="me-2" />
                <div class="flex-grow-1">
                  <el-input type="textarea" :rows="2" placeholder="添加评论..." v-model="newCommentContent" />
                  <div class="d-flex justify-content-between align-items-center mt-2">
                    <el-button size="small"><i class="bi bi-emoji-smile"></i></el-button>
                    <el-button type="primary" size="small" @click="addComment">发布</el-button>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>
    <el-skeleton v-else :rows="5" animated />
    <div v-if="replyContextMenu.visible" class="context-menu"
      :style="{ top: replyContextMenu.y + 'px', left: replyContextMenu.x + 'px' }">
      <div class="context-menu-item" @click.stop="requestDeleteReply">
        删除回复
      </div>
    </div>
  </el-dialog>

</template>

<script setup>
import { ref, watch, computed, reactive, nextTick } from 'vue';
import { useForumStore } from '@/stores/forum.js'; // 1. 导入 forumStore
import { ElMessage } from 'element-plus'; // 引入 ElMessage
import { Position } from '@element-plus/icons-vue';
import { useUserStore } from '@/stores/user.js';
import { onMounted, onUnmounted } from 'vue'; // 引入生命周期钩子
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import 'dayjs/locale/zh-cn';

dayjs.extend(relativeTime);
dayjs.locale('zh-cn');
const userStore = useUserStore(); // 实例化用户 store
// ++ 新增：用于回复的右键菜单 ++
const replyContextMenu = ref({
  visible: false,
  x: 0,
  y: 0,
});
const commentRefs = ref(new Map());

const setCommentRef = (el, id) => {
  if (el) {
    commentRefs.value.set(id, el);
  }
};
const replyToDelete = ref(null);
const props = defineProps({
  modelValue: Boolean,
  post: {
    type: Object,
    default: () => null // 将默认值改为 null
  },
  currentUserId: { // 新增此属性
    type: Number,
    default: null
  }
});
const showReplyContextMenu = (event, comment) => {
  // 只有评论作者本人或管理员才能显示菜单
  if (comment.authorId === props.currentUserId || userStore.isAdmin) {
    replyContextMenu.value.visible = true;
    replyContextMenu.value.x = event.clientX;
    replyContextMenu.value.y = event.clientY;
    replyToDelete.value = comment;
  }
};

// ++ 新增：隐藏回复的右键菜单 ++
const hideReplyContextMenu = () => {
  replyContextMenu.value.visible = false;
};

// ++ 新增：请求删除回复，并发出事件 ++
const requestDeleteReply = () => {
  if (replyToDelete.value) {
    emit('delete-reply', replyToDelete.value); // 发出事件，将整个评论对象传出去
  }
  hideReplyContextMenu();
};

// ++ 新增：添加和移除全局点击监听器 ++
onMounted(() => {
  window.addEventListener('click', hideReplyContextMenu);
});

onUnmounted(() => {
  window.removeEventListener('click', hideReplyContextMenu);
});
const emit = defineEmits(['update:modelValue', 'delete-reply']);
const forumStore = useForumStore();
const visible = ref(props.modelValue);
const newCommentContent = ref('');
const liked = ref(false);
const likedCommentIds = reactive(new Set());
// --- 新增状态：用于管理“回复的回复” ---
const replyingTo = ref(null); // 存储正在回复的评论对象
const subReplyContent = ref(''); // 存储子回复的输入内容

// 使用计算属性安全地访问嵌套数据
const likeCount = computed(() => props.post?.forumPost?.likes || 0);
const toggleCommentLike = (comment) => {
  if (likedCommentIds.has(comment.id)) {
    likedCommentIds.delete(comment.id); // 如果已存在，则删除（取消点赞）
    console.log(`评论 ${comment.id} 取消点赞`);
  } else {
    likedCommentIds.add(comment.id); // 如果不存在，则添加（点赞）
    console.log(`评论 ${comment.id} 已点赞`);
  }
};
watch(() => props.modelValue, async (val) => {
  visible.value = val;
  if (val) {
    likedCommentIds.clear(); // 清空点赞记录
    // 新增：检查并执行高亮逻辑
    await nextTick(); // 等待DOM完全渲染
    const highlightId = parseInt(sessionStorage.getItem('highlightReplyId'));
    if (highlightId) {
      const targetElement = commentRefs.value.get(highlightId);
      if (targetElement) {
        // 滚动到元素位置并添加高亮 class
        targetElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
        targetElement.classList.add('highlight-reply');
        // 2秒后移除高亮效果
        setTimeout(() => {
          targetElement.classList.remove('highlight-reply');
        }, 2000);
      }
      // 用完后立即清除，防止干扰
      sessionStorage.removeItem('highlightReplyId');
    }
  } else {
    replyingTo.value = null; // 关闭时重置回复状态
    subReplyContent.value = '';
  }
});
watch(visible, (val) => { emit('update:modelValue', val); });


// const hierarchicalReplies = computed(() => {
//   if (!props.post || !props.post.replyList) return [];

//   const replies = props.post.replyList;
//   const replyMap = new Map(replies.map(r => [r.id, { ...r, children: [] }]));
//   const topLevelReplies = [];

//   for (const reply of replies) {
//     if (reply.fromReply) {
//       const parent = replyMap.get(reply.fromReply);
//       if (parent) {
//         parent.children.push(replyMap.get(reply.id));
//       }
//     } else {
//       topLevelReplies.push(replyMap.get(reply.id));
//     }
//   }

//   // --- 新增：对每个父评论的子评论进行排序 ---
//   for (const parentReply of topLevelReplies) {
//     if (parentReply.children.length > 1) {
//       parentReply.children.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
//     }
//   }
//   // --- 新增结束 ---

//   // 按时间倒序排列顶级回复
//   return topLevelReplies.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
// });

// --- 修改：将扁平列表转换为支持“楼中楼”的二级结构 ---
const hierarchicalReplies = computed(() => {
  if (!props.post || !props.post.replyList) return [];

  const replies = props.post.replyList;
  const replyMap = new Map(replies.map(r => [r.id, { ...r, children: [] }]));
  const topLevelReplies = [];

  // 这个循环的目的是将所有子回复都归到其顶级父回复的 children 数组中
  for (const reply of replies) {
    let parentId = reply.fromReply;
    let parent = parentId ? replyMap.get(parentId) : null;

    // 如果有父ID，但父评论本身也是一个子评论，则继续向上找顶级父评论
    while (parent && parent.fromReply) {
      parentId = parent.fromReply;
      parent = replyMap.get(parentId);
    }

    if (parent) { // 找到了顶级父评论
      parent.children.push(reply);
    } else { // 没有父ID，说明它自己就是顶级评论
      topLevelReplies.push(replyMap.get(reply.id));
    }
  }

  // 对每个父评论的子评论按时间升序排列（旧的在前，新的在后）
  for (const parentReply of topLevelReplies) {
    if (parentReply.children.length > 1) {
      parentReply.children.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
    }
  }

  // 对顶级评论按时间倒序排列（最新的在前）
  return topLevelReplies.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
});


const handleClose = () => {
  visible.value = false;
};

const toggleLike = () => {
  // 点赞逻辑
  liked.value = !liked.value;
};

// const addComment = () => {
//   if (newCommentContent.value.trim() && props.post && props.post.forumPost) {
//     const replyData = {
//         // 对于一级回复，FatherReplyId 为 null
//         fatherReplyId: null, 
//         content: newCommentContent.value.trim()
//     };

//     // 调用 store action 来发送回复
//     forumStore.createReply(
//         props.post.forumPost.id, 
//         replyData,
//         () => {
//             // 发送成功后的回调
//             newCommentContent.value = '';
//             // 可选：立即刷新一次评论列表，以获得最即时（但非实时）的更新
//             forumStore.fetchPostThread(props.post.forumPost.id);
//         }
//     );
//   }
// };
// 发送一级回复 (回复帖子)
const addComment = () => {
  if (newCommentContent.value.trim() && props.post?.forumPost) {
    const replyData = {
      fatherReplyId: null,
      content: newCommentContent.value.trim()
    };
    forumStore.createReply(props.post.forumPost.id, replyData, () => {
      newCommentContent.value = '';
      forumStore.fetchPostThread(props.post.forumPost.id);
    });
  }
};

// --- 新增：点击“回复”按钮的事件 ---
const showSubReplyInput = (comment) => {
  replyingTo.value = (replyingTo.value && replyingTo.value.id === comment.id) ? null : comment;
  subReplyContent.value = ''; // 每次都清空输入框
};

// --- 新增：发送“回复的回复” ---
const sendSubReply = () => {
  if (subReplyContent.value.trim() && replyingTo.value) {
    const replyData = {
      fatherReplyId: replyingTo.value.id, // 关键：设置父回复ID
      content: subReplyContent.value.trim()
    };
    forumStore.createReply(props.post.forumPost.id, replyData, () => {
      subReplyContent.value = '';
      replyingTo.value = null; // 发送后隐藏输入框
      forumStore.fetchPostThread(props.post.forumPost.id);
    });
  }
};


</script>

<style scoped>
/* 保持之前的样式 */

@keyframes highlight-fade {
  from {
    background-color: rgba(255, 230, 153, 0.8);
  }

  to {
    background-color: transparent;
  }
}

.highlight-reply {
  animation: highlight-fade 2s ease-out;
  border-radius: 4px;
  /* 让高亮背景有圆角，更好看 */
}

.row {
  display: flex;
}

.context-menu {
  position: fixed;
  z-index: 9999;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  min-width: 120px;
  padding: 4px 0;
}

.context-menu-item {
  padding: 8px 16px;
  font-size: 14px;
  color: #333;
  cursor: pointer;
  white-space: nowrap;
}

.context-menu-item:hover {
  background-color: #f5f7fa;
}

.col-md-7 {
  width: 58.33%;
}

.col-md-5 {
  width: 41.67%;
}

.border-end {
  border-right: 1px solid #e4e7ed;
}

.comment-list {
  max-height: 400px;
  overflow-y: auto;
}

/* 新增样式 */
.author-me {
  font-weight: bold;
  color: var(--el-color-primary);
}

.sub-reply-list {
  background-color: #f8f9fa;
  padding-top: 10px;
  border-radius: 4px;
}

.sub-reply-input .el-input-group__append {
  padding: 0 10px;
}
</style>